package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author ck
 * @date 2021/11/19 13:12
 */

@Service
public class ManageService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //分页查询用户列表
    public PageResult findAllUsers(Integer page, Integer pagesize) {

        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        List<UserInfo> records = iPage.getRecords();
        for (UserInfo record : records) {
            //查询redis中的冻结状态
            String key = Constants.USER_FREEZE + record.getId();
            if (redisTemplate.hasKey(key)){
                record.setUserStatus("2");
            }
        }
        return new PageResult(page, pagesize, iPage.getTotal(),iPage.getRecords());
    }

    //根据id查询
    public ResponseEntity findById(Long userId) {
        UserInfo userinfo = userInfoApi.findById(userId);

        //查询redis中的冻结状态
        String key = Constants.USER_FREEZE + userId;
        if (redisTemplate.hasKey(key)){
            userinfo.setUserStatus("2");
        }
        return ResponseEntity.ok(userinfo);
    }

    //查询视频记录
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        //查询用户数据
        UserInfo userInfo = userInfoApi.findById(uid);
        //查询用户发布的所有视频
        List<Video> videos = videoApi.findByUid(page, pagesize, uid);
        //构建vo对象
        List<VideoVo> list = new ArrayList<>();
        for (Video item : videos) {
            VideoVo vo = VideoVo.init(userInfo, item);
            list.add(vo);
        }
        //4、构造返回
        return new PageResult(page, pagesize, 0l, list);
    }

    //查询动态记录
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //1、调用api获取 Movement对象
        PageResult pageResult = movementApi.findByUserIds(uid, state, page, pagesize);
        //2、解析Pageresult：获取movement对象列表
        List<Movement> items = (List<Movement>) pageResult.getItems();
        //3、一个Movement对象转化为一个Vo
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }

        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);

        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = map.get(item.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, item);
                vos.add(vo);
            }
        }
        //4、构造返回值
        pageResult.setItems(vos);
        return pageResult;
    }

    //查询动态详情
    public MovementVooo findMovementVo(String movementId) {

        Movement movement = movementApi.findById(movementId);
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());

        MovementVooo vo = new MovementVooo();
        vo.setAvatar(userInfo.getAvatar());
        vo.setNickname(userInfo.getNickname());
        vo.setId(movement.getId().toHexString());
        vo.setUserId(userInfo.getId());
        vo.setTextContent(movement.getTextContent());
        vo.setCreateDate(movement.getCreated());
        vo.setLikeCount(movement.getLikeCount());
        vo.setState(movement.getState());
        vo.setCommentCount(movement.getCommentCount());
        List<String> medias = movement.getMedias();
        String[] arr = new String[medias.size()];

        for (int i = 0; i < arr.length; i++) {
            arr[i] = medias.get(i);
        }

        vo.setImageContent(arr);
        return vo;
    }

    public PageResult findMessageVo(Integer page, Integer pagesize, ObjectId id) {
        PageResult pr = commentApi.findComment(page, pagesize, id);
        List<Comment> items = (List<Comment>) pr.getItems();
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findList(ids);
        List<MessageVo> vos = new ArrayList<>();

        for (Comment item : items) {
            UserInfo userInfo = userInfoMap.get(item.getUserId());
            if (userInfo != null) {
                MessageVo vo = new MessageVo();
                vo.setId(item.getId().toHexString());
                vo.setNickname(userInfo.getNickname());
                vo.setUserId(userInfo.getId());
                vo.setContent(item.getContent());
                vo.setCreateDate(item.getCreated());
                vos.add(vo);
            }
        }
        pr.setItems(vos);
        return pr;
    }


    //用户冻结
    public Map userFreeze(Map params) {
        //1、构造key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //2、构造失效时间

//        冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString());
        int days = 0;
        if (freezingTime == 1) {
            days = 3;
        } else if (freezingTime == 2) {
            days = 7;
        }
        //3、将数据存入redis
        String value = JSON.toJSONString(params);
        if (days > 0) {
            redisTemplate.opsForValue().set(key, value, days, TimeUnit.MINUTES);
        } else {
            redisTemplate.opsForValue().set(key, value);
        }

        Map retMap = new HashMap();
        retMap.put("message", "冻结成功");

        return retMap;
    }

    //用户解冻
    public Map userUnfreeze(Map params) {
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //删除redis数据
        redisTemplate.delete(key);

        Map retMap = new HashMap();
        retMap.put("message", "解冻成功");

        return retMap;
    }
}
